﻿using Microsoft.Extensions.DependencyInjection;
using ShardingCore;
using Volo.Abp;
using Volo.Abp.Modularity;

namespace Gateway.Domain.EFCore
{
    /// <summary>
    /// 
    /// </summary>
    [DependsOn()]
    public class EFCoreAbpModule : AbpModule
    {
        public override Task ConfigureServicesAsync(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            // var name = Assembly.GetExecutingAssembly().GetName().Name;
            var name = typeof(EFCoreAbpModule).Assembly.GetName().Name!;
            context.Services.AddEF(configuration, migrationAssembly: name);
            return base.ConfigureServicesAsync(context);
        }

        public override async Task OnApplicationInitializationAsync(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var dbContext = app.ApplicationServices.CreateScope()?.ServiceProvider?.GetService<Domain.EFCore.ShareCoreDbContext>();
            if (dbContext != null)
            {
                // 不使用迁移记录生成
                await dbContext.Database.EnsureCreatedAsync();
                // await dbContext.Database.MigrateAsync();
                await Console.Out.WriteLineAsync("create database success:");
            }
            // 如果需要在启动后扫描是否有表缺少了可以添加这个
            //app.MigrateDbContext<ShareCoreDbContext>();
            app.ApplicationServices.UseAutoTryCompensateTable();
            await base.OnApplicationInitializationAsync(context);
        }
    }
}
